package com.eventbus.monitor;

import com.google.common.eventbus.EventBus;

import java.nio.file.*;

/**
 * Created by Lxk on 2020/7/25.
 */
public class DirTargetMonitor implements TargetMonitor {

    private WatchService watchService;

    private EventBus eventBus;

    private Path path;

    private volatile boolean start = false;

    public DirTargetMonitor(EventBus eventBus, String path) {
        this(eventBus,path,"");
    }

    public DirTargetMonitor(EventBus eventBus, String path,String ...morePath) {
        this.eventBus = eventBus;
        this.path = Paths.get(path,morePath);
    }


    @Override
    public void startMonitor() throws Exception {
        this.watchService = FileSystems.getDefault().newWatchService();
        this.path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE);
        System.out.println("Monitor " + this.path + "is running!!");
        this.start = true;
        while(start){
            WatchKey watchKey = null;
            try{
                watchKey = watchService.take();
                watchKey.pollEvents().forEach(each -> {
                    WatchEvent.Kind kind = each.kind();
                    Path tmpPath = (Path) each.context();
                    Path childPath = path.resolve(tmpPath);
                    eventBus.post(new FileChangeEvent(childPath,kind));
                });
            }catch (Exception e){
                this.start = false;
            }finally {
                if(watchKey != null){
                    watchKey.reset();
                }
            }
        }
    }

    @Override
    public void stopMonitor() throws Exception {
        System.out.println("monitor will be stopped!!");
        this.start = false;
        this.watchService.close();
    }
}
